<template>
	<view class="content">
		<view class="loginForm">
			<u--form labelPosition="left" :model="model" :rules="rules" ref="uForm">
				<u-form-item label="姓名:" prop="userInfo.name" borderBottom ref="item1" labelWidth="auto"
					:required="isRequired">
					<u--input v-model="model.userInfo.name" border="none" :inputAlign="positionInput"
						:maxlength="inputMaxLength.nameLength"></u--input>
				</u-form-item>
				<u-form-item label="手机号:" prop="userInfo.phone" borderBottom ref="item1" labelWidth="auto"
					v-if="registrationFlag" :required="isRequired">
					<u--input v-model="model.userInfo.phone" border="none" :inputAlign="positionInput" :clearable="true"
						:maxlength="inputMaxLength.phoneLength"></u--input>
					<view class="wrap" slot="right">
						<u-toast ref="uToast"></u-toast>
						<u-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange"></u-code>
						<u-button @tap="getCode" color="#1ba784" size="mini">{{tips}}</u-button>
					</view>
				</u-form-item>
				<u-form-item label="密码:" prop="userInfo.password" borderBottom ref="item1" labelWidth="auto"
					:required="isRequired">
					<u--input v-model="model.userInfo.password" border="none" :inputAlign="positionInput"
						type="password" :clearable="true" :maxlength="inputMaxLength.passwordLength"></u--input>
				</u-form-item>
				<u-form-item label="确认密码:" prop="userInfo.passwordConfirm" borderBottom ref="item1" labelWidth="auto"
					v-if="registrationFlag" :required="isRequired">
					<u--input v-model="model.userInfo.passwordConfirm" border="none" :inputAlign="positionInput"
						type="password" :clearable="true" :maxlength="inputMaxLength.passwordLength"></u--input>
				</u-form-item>
				<u-form-item label="验证码:" prop="userInfo.code" borderBottom ref="item1" labelWidth="auto"
					v-if="registrationFlag" :required="isRequired">
					<u-code-input slot="right" class="codeInput" v-model="model.userInfo.code" mode="line"
						borderColor="#f6f6f4" dot :focus="true" size="25" space="5"></u-code-input>
				</u-form-item>
			</u--form>
			<view class="registration">
				<u-button type="primary" size="small" :text="loginPatternText" shape="circle" @click="registration()"
					:color="registrationButtonColor"></u-button>
			</view>
			<view class="submit">
				<u-button type="primary" :text="loginText" :color="submitButtonColor" @click="submit()"
					shape="circle"></u-button>
			</view>
			<view class="sexPicker">
				<u-picker :show="sexPickerShow" ref="uPicker" :columns="columns" @confirm="confirm" @cancel="cancel()"
					confirmColor="#1ba784"></u-picker>
			</view>
			<view class="alert">
				<u-alert :title="title" type="error" :show-icon="alertStatus" :closable="alertStatus"
					v-if="alertStatus"></u-alert>
			</view>
		</view>
		<!-- 消息提示框组件 -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//发送验证码
				tips: '',
				//重新获取验证码的时间
				seconds: 60,
				//输入框位置
				positionInput: "left",
				//输入框长度限制
				inputMaxLength: {
					nameLength: 6,
					phoneLength: 11,
					passwordLength: 12,
				},
				//是否为必填项
				isRequired: true,
				showSex: false,
				model: {
					userInfo: {
						id: "",
						name: '',
						sex: '',
						phone: '',
						password: '',
						code: "",
						passwordConfirm: ''
					},
				},
				//注册title
				registrationTitle: "用户注册",
				//登录title
				loginTitle: "用户登录",
				// 注册flag
				registrationFlag: false,
				registrationButtonColor: "#3c9cff",
				submitButtonColor: "#1ba784",
				// 登录按钮文本
				loginText: "登录",
				//登录方式文本
				loginPatternText: "未有账号?点此进行注册",
				// 数据校验规则
				rules: {
					//姓名校验规则
					'userInfo.name': [{
						type: "string",
						required: true,
						message: "姓名不能为空",
						trigger: ['change', 'blur']
					}, {
						min: 1,
						max: 6,
						message: '昵称在1-6个字符之间',
						trigger: ['change', 'blur']
					}],
					//性别校验规则
					// 'userInfo.sex': {
					// 	type: "string",
					// 	required: true,
					// 	message: "性别不能为空"
					// },
					//密码校验规则
					'userInfo.password': [{
							type: "string",
							required: true,
							message: "密码不能为空",
							trigger: ['change', 'blur']
						},
						//对密码长度进行校验
						{
							min: 6,
							max: 12,
							message: "密码长度在6-12位",
							trigger: ['change', 'blur']
						},
						//对密码进行正则校验
						{
							pattern: /^[A-Za-z0-9]+$/,
							transform(value) {
								return String(value);
							},
							message: '密码只由数字和字母组成',
							trigger: ['change', 'blur']
						}
					],
					//密码校验规则
					'userInfo.passwordConfirm': [{
							type: "string",
							required: true,
							message: "密码不能为空",
							trigger: ['change', 'blur']
						},
						//对密码长度进行校验
						{
							min: 6,
							max: 12,
							message: "密码长度在6-12位",
							trigger: ['change', 'blur']
						},
						//对密码进行正则校验
						{
							pattern: /^[A-Za-z0-9]+$/,
							transform(value) {
								return String(value);
							},
							message: '密码只由数字和字母组成',
							trigger: ['change', 'blur']
						}
					],
					// 验证码校验规则 
					'userInfo.code': [{
							type: "string",
							required: true,
							message: "验证码不能为空"
						},
						{
							len: 6,
							message: "验证码长度在6位",
							trigger: ['change', 'blur']
						},
						//对验证码进行校验
						{
							pattern: /^\d+$/,
							transform(value) {
								return String(value);
							},
							message: '验证码只由数字组成',
							trigger: ['change', 'blur']
						}
					],
					//手机号校验规则
					'userInfo.phone': [{
							required: true,
							message: "手机号未填",
						},
						//对手机号长度进行校验
						{
							len: 11,
							message: "手机号长度为11位"
						},
						//对手机号规范进行正则校验
						{
							pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
							transform(value) {
								return String(value);
							},
							message: '手机号不符合规范',
							trigger: ['change', 'blur']
						}
					]
				},
				sexPickerShow: false,
				columns: [
					['男', '女', '保密']
				],
				//person
				personInfo: {},
				//对注册表单校验合格的标记
				registrationFormFlag: true,
				//
				title: '请确保密码一致',
				//alert本身和额外样式是否开启
				alertStatus: false,
				//showToast的list
				ToastList: [{
					type: 'success',
					title: '成功主题(带图标)',
					message: "注册成功!",
					duration: 1000,
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
				}, {
					type: 'error',
					title: '失败主题',
					message: "注册失败",
					duration: 1000,
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
				}, {
					type: 'success',
					title: '成功主题(带图标)',
					message: "登录成功!正跳转至个人页",
					duration: 1000,
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
				}]
			}
		},
		methods: {
			//点击原先注册按钮时,进行样式切换
			registration() {
				this.switchButtonStyle();
			},
			//按钮之间进行交换
			switchButtonStyle() {
				if (!this.registrationFlag) {
					this.registrationFlag = true;
					console.log("注册")
					this.loginText = "注册";
					this.loginPatternText = "已有账号?登录";
					this.switchColor()
					//更改标题
					this.switchTitle(this.registrationTitle);
				} else {
					this.registrationFlag = false;
					this.loginText = "登录";
					console.log("登录")
					this.loginPatternText = "未有账号?点此进行注册";
					this.switchColor()
					this.switchTitle(this.loginTitle);
				}
			},
			//更改标题
			switchTitle(title) {
				uni.setNavigationBarTitle({
					title: title
				})
			},
			//交换颜色
			switchColor() {
				let that = this.submitButtonColor;
				this.submitButtonColor = this.registrationButtonColor;
				this.registrationButtonColor = that;
			},
			confirm(e) {
				//解构value
				const {
					value
				} = e;
				this.model.userInfo.sex = value[0];
				//修改缓存
				this.cancel();
			},
			cancel() {
				//关闭下拉选择框
				this.sexPickerShow = false;
			},
			sexPickerShowMethods() {
				this.sexPickerShow = true;
			},
			//提交按钮
			submit() {
				if (!this.registrationFlag) {
					//用户选择登录
					//登录之前只对name和password进行校验
					//定义一个变量,用户判断此时校验是否通过
					let isRule = true;
					this.$refs.uForm.validateField('userInfo.name', res => {
						//对回调函数的res数组进行长度判断,为0表示该字段校验通过
						if (res.length) {
							isRule = false;
						}
					})
					this.$refs.uForm.validateField('userInfo.password', res => {
						//对回调函数的res数组进行长度判断,为0表示该字段校验通过
						if (res.length) {
							isRule = false;
						}
						if (isRule) {
							this.userLogin();
						}
					})

				} else {
					//用户选择注册
					//提交之前对整个表单进行校验

					this.$refs.uForm.validate().then(res => {
						//TODO 还需要进行验证码验证,这里暂时先不做
						if (this.model.userInfo.password === this.model.userInfo.passwordConfirm) {
							this.userRegister();
						} else {
							//开启alert及其样式
							console.log("alertStatus open");
							this.alertStatus = true;
						}
					}).catch(res => {

					})
				}
				console.log(this.model.userInfo);
			},
			//登录封装方法
			userLogin() {
				this.$request("/user/login", "GET", {
					name: this.model.userInfo.name,
					password: this.model.userInfo.password
				}).then(res => {
					//解构data
					let {
						data
					} = res;
					if (data.code === 1 || data.code == 200) {
						data.data.user.sex = data.data.user.sex;
						let person = {
							id: data.data.user.id,
							nickName: data.data.user.name,
							sex: data.data.user.sex,
							phone: data.data.user.phone,
							avatarUrl: data.data.user.avatarUrl
						}
						//存token
						uni.setStorageSync("token", data.data.token);
						uni.setStorageSync("refreshToken", data.data.refreshToken);
						//更新缓存
						uni.setStorageSync("personInfo", person);
						//触发isLogin自定义事件
						uni.$emit("isLogin", true);
						//登录成功
						this.showToast(this.ToastList[2]);
						//进行路由跳传
						uni.switchTab({
							url: "/pages/my/my"
						})
					}
				})
			},
			//用户注册方法
			userRegister() {
				//注册接口,数据格式json
				this.$request("/user/signIn", "POST", {
					name: this.model.userInfo.name,
					password: this.model.userInfo.password,
					sex: this.model.userInfo.sex,
					phone: this.model.userInfo.phone,
					//TODO 先写死-默认年龄
					age: 18
				}, {
					'content-type': "application/json"
				}).then(res => {
					if (res.data.code == 1 || res.data.code == 200) {
						//注册成功消息提示
						this.showToast(this.ToastList[0]);
						//换成登录按钮
						this.switchButtonStyle();
					} else {
						//注册失败消息提示
						this.showToast(this.ToastList[1]);
					}
				}).catch(error => {
					console.log(`${error.data.message}`);
				})
			},
			//获取验证码相关
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				this.$refs.uForm.validateField('userInfo.phone', res => {
					if (this.$refs.uCode.canGetCode && res.length <= 0) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码'
						})
						setTimeout(() => {
							uni.hideLoading();

							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
							//发送验证码
							this.$request("/user/phoneSignIn", "GET", {
								phone: this.model.userInfo.phone
							}, {
								token: uni.getStorageSync("token")
							}).then(res => {
								// 这里此提示会被this.start()方法中的提示覆盖
								uni.$u.toast('验证码已发送');
							}).catch(error => {
								console.log(`${error.data.message}`);
							})
						}, 2000);
					} else {
						if (res.length > 0) {
							uni.$u.toast('输入正确的手机号');
							return;
						}
						if (!this.$refs.uCode.canGetCode) {
							uni.$u.toast("验证码已发送")
						}
					}
				})

			},
			//倒计时结束
			end() {

			},
			// 倒计时开始
			start() {

			},
			//showToast
			showToast(params) {
				this.$refs.uToast.show({
					...params,
				})
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style lang="scss" scoped>
	// .codeInput {
	// 	margin-top: 5%;
	// }
	//发送验证码的样式
	.wrap {
		padding: 5rpx;
	}

	.loginForm {
		padding: 5% 5%;
	}

	.content {
		position: relative;

		.registration {
			position: absolute;
			right: 5%;
			width: 40%;
			margin-top: 5%;
		}

		//提交按钮样式
		.submit {
			margin-top: 16%;
		}

		.alert {
			margin-top: 5%;
		}
	}

	//注册按钮样式
</style>